package com.i2silly.wxbot.utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON工具类
 * 
 * @author kwufa@linewell.com
 * @date 2015年5月21日 上午11:06:53
 */
public class JsonUtil {

	private static String DEFAULT_NULL = "null";// 默认空

	/**
	 * 初始化""的日期为默认null
	 * 
	 * @param jsonStr json字符串
	 * @param columnName 日期key
	 * @return 初始化过的日期
	 */
	private static String initEmptyDate(String jsonStr, String columnName) {
		if (jsonStr.contains("\"" + columnName + "\":\"\"")) {
			return jsonStr.replace("\"" + columnName + "\":\"\"", "\"" + columnName + "\":" + DEFAULT_NULL + "");
		} else {
			return jsonStr;
		}
	}

	/**
	 * 解析前台JSON串，转成后台对象
	 */
	public static <T> T fromJson(String objJsonStr, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		// json有的key，对象没有属性会报错的问题
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
		T obj = null;
		try {
			// 日期非空处理
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				if (fields[i].getType() == java.sql.Timestamp.class) {
					objJsonStr = initEmptyDate(objJsonStr, fields[i].getName());
				}
			}
			obj = mapper.readValue(objJsonStr, clazz);

		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e.getMessage());
		}
		return obj;
	}
	
	/**
	 * 解析前台JSON串，转成后台对象
	 */
	public static <T> T fromJson(String objJsonStr, Class<T> clazz, DateFormat format) {
		ObjectMapper mapper = new ObjectMapper();
		// json有的key，对象没有属性会报错的问题
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setDateFormat(format);
		
		T obj = null;
		try {
			// 日期非空处理
			Field[] fields = clazz.getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				if (fields[i].getType() == java.sql.Timestamp.class) {
					objJsonStr = initEmptyDate(objJsonStr, fields[i].getName());
				}
			}
			obj = mapper.readValue(objJsonStr, clazz);

		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		} catch (IllegalArgumentException e) {
			throw new RuntimeException( e.getMessage());
		}
		return obj;
	}

	/**
	 * 对象转字符串
	 */
	public static String toJson(Object object) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			throw new RuntimeException( e.getMessage());
		}
	}

	/**
	 * 解析前台JSON数组字符串，转成后台对象
	 */
	public static <T> List<T> fromJsonArray(String objJsonStr, Class<T> clazz) {
		List<T> list = new ArrayList<T>();
		objJsonStr = objJsonStr.substring(1, objJsonStr.length() - 1);// 去除[{},{},...]中的[]
		int index = objJsonStr.indexOf("},{");
		if (index > 0) {// 包含两个以上{}
			String firstHalf = objJsonStr.substring(0, index + 1);// 第一个逗号前半段
			String secondHalf = objJsonStr.substring(index + 2);// 第一个逗号后半段
			list.add(fromJson(firstHalf, clazz));
			list.addAll(fromJsonArray("[" + secondHalf + "]", clazz));
		} else {// 不包含或只包含一个{}
			if (objJsonStr.length() > 1) {
				list.add(fromJson(objJsonStr, clazz));
			}
		}
		return list;
	}
	
	/**
	 * 解析前台JSON数组字符串，转成后台对象
	 */
	// 转换不了pivpIdcardController/queryTimeChart
	/*public static <T> List<T> fromJsonArray(String objJsonStr, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		List<T> result = new ArrayList<T>();
		
		try {
			List<Map<String, Object>> objList = mapper.readValue(objJsonStr, List.class);
			
			for (Map<String, Object> obj : objList) {
				T bean = clazz.newInstance();
				BeanUtil.transMap2Bean(obj, bean);
				result.add(bean);
			}
			
			return result;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}*/

	public static void main(String[] args) {
		/*String json = "{\"createTime\":\"2016-08-16 17:26:00\"}";
		
		CfgModule module = fromJson(json, CfgModule.class, new SimpleDateFormat(DateUtil.DATETIME_FORMAT));
		
		System.out.println(module.getCreateTime());*/
		try{
			String json = "{\"areaUnid\":\"\",\"faceUrl\":\"http://44.112.0.220/213482e9c0e37fa24bf496124454fc44.jpg?OSSAccessKeyId=v4SP3g69Gq0074N9qN19UuD2P74uHdjx&Expires=1678982400&Signature=bWn%2BT09zUrY3dkFer12fOXtPxIc%3D&Bucket=35050050\",\"picUrl\":\"http://44.112.2.138:18080/shrekapi/image/cloudImgStream?origUrl=aHR0cDovLzM1LjEwMC4yMjQuMTA2OjgwL2Y3MGIyN2UxNTk0ZTQ3ZjliODhkMGNiNjcyNjkwNDA0LmpwZz9PU1NBY2Nlc3NLZXlJZCUzREhJS3Q0TTBZNjFxMmU2QjlBMEpaMDMwQTlwMzBlVTB4JTI2RXhwaXJlcyUzRDE3MTA2MDQ4MDAlMjZTaWduYXR1cmUlM0RzeEZ3cmFKZHlWOHhhbk5tVWd5dTV5U3ZTWUUlM0QlMjZCdWNrZXQlM0QzNTA1MjQxMg==\",\"msgDagNo\":\"35050301\",\"unid\":\"\",\"msgType\":\"1\",\"pointCode\":\"\",\"pointId\":\"\",\"devCode\":\"35058372011320000585\",\"captureTime\":\"1615973151203\",\"msgName\":\"faceCapture\",\"msgDate\":\"1615973160258\"}";
			FaceCaptureMsg faceCaptureMsg = JsonUtil.fromJson(json, FaceCaptureMsg.class);
			System.out.println(faceCaptureMsg);

		}catch (Exception e) {
			System.out.println(e.getMessage());
		}


	}
}
